import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
// JS向flutter传递数据，通过URL
const String htmlStr = '''
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title>通过URL向flutter传递参数</title>
</head>
<body>
  <button id="btn" style="font-size: 2.5em">传递参数</button>
  <script type="text/javascript">
    var btn = document.getElementById("btn");
    btn.addEventListener('click',function(){
      //通过URL向flutter传递参数
      document.location = "hi://webview?name=geekcc";
    },false)
  </script>
</body>
</html>
''';
class Js2flutterByUrl extends StatefulWidget {
  const Js2flutterByUrl({super.key});

  @override
  State<Js2flutterByUrl> createState() => _Js2flutterByUrlState();
}

class _Js2flutterByUrlState extends State<Js2flutterByUrl> {
  late WebViewController controller;

  get _loadBtn => FilledButton(onPressed: (){
    controller.loadHtmlString(htmlStr);// 加载 html 字符串为页面并展示
  }, child: const Text(
    '加载H5页面', style: TextStyle(color: Colors.white),
  ));
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('JS向Flutter传递数据'),
        actions: [_loadBtn],
      ),
      body: WebViewWidget(controller: controller),
    );
  }

  @override
  void initState() {
    super.initState();
    controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setNavigationDelegate(NavigationDelegate(onNavigationRequest: (NavigationRequest request){
      // 约定的通讯协议：hi://webview
      if(request.url.startsWith('hi://webview')){
        debugPrint('处理JS通过URL传递过来的数据：$request');
        Uri uri = Uri.parse(request.url);
        // 解析URL参数
        var name = uri.queryParameters['name'];
        debugPrint('name:$name');
        ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('name:$name')));
        return NavigationDecision.prevent;
      }else{
        return NavigationDecision.navigate;
      }
    }))
    ;
  }
}
